import { createStore,applyMiddleware,combineReducers } from "redux";
import logger from 'redux-logger'
import thunk from 'redux-thunk'

// actionTypes
const ADD='ADD'
const DELETE='DELETE'
const INIT='INIT'
// listReducer
const innitialState=[
  {
    username:'',
    content:''
  }
]
const listReducer=(state=innitialState,action)=>{
  switch (action.type){
    case INIT:
      return action.payload
    case ADD:
      return [...state,action.payload]
    case DELETE:
      return [
        ...state.slice(0,action.payload),
        ...state.slice(action.payload+1)
      ]
    default:
      return state
  }
}
// actionCreators
export const initList=(list)=>(
  {type:INIT,payload:list}
)
export const addList=(item)=>(
  {type:ADD,payload:item}
)
export const deleteList=(index)=>(
  {type:DELETE,payload:index}
)
export const asyncList=()=>(dispatch)=>(
  dispatch({
    type:INIT,
    payload:[{
      username:'async',
      content:'我是异步数据'
    }]
  })
)

// userReducer
const userReducer=(state={isLogin:false},action)=>{
  switch(action.type){
    case 'Login':
      return {isLogin:true}
    case 'Logout':
      return {isLogin:false}
    default:
      return state
  }
}
export const login=()=>(
  {type:'Login'}
)
export const logout=()=>(
  {type:'Logout'}
)
// store
const store=createStore(
  combineReducers({list:listReducer,user:userReducer}),
  applyMiddleware(logger,thunk)
)
export default store